package com.myblog.myblog.utils;

import cn.hutool.core.util.IdUtil;
import com.myblog.myblog.constant.Constant;
import com.myblog.myblog.domain.TaskJob;
import com.myblog.myblog.domain.TaskJobLog;
import com.myblog.myblog.mapper.TaskJobLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务工具
 * @author gyl
 * @data 2020/5/3 17:20
 */
@Component
@Slf4j
public class ScheduleJobUtils extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Autowired
    private TaskJobLogMapper taskJobLogMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        TaskJob taskJob = (TaskJob) jobExecutionContext.getMergedJobDataMap().get(Constant.JOB_PARAM_KEY);

        TaskJobLog taskJobLog = new TaskJobLog();
        taskJobLog.setId(IdUtil.simpleUUID());
        taskJobLog.setTaskId(taskJob.getId());
        taskJobLog.setBeanName(taskJob.getBeanName());
        taskJobLog.setMethodName(taskJob.getMethodName());
        taskJobLog.setParam(taskJob.getParam());
        taskJobLog.setCreateTime(new Date());

        long startTime = System.currentTimeMillis();

        try{

            //执行任务
            log.info("任务准备执行，任务ID：" + taskJob.getId());
            ScheduleRunnable scheduleRunnable = new ScheduleRunnable(taskJob.getBeanName(), taskJob.getMethodName(), taskJob.getParam());
            Future<?>  future = service.submit(scheduleRunnable);
            future.get();

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            taskJobLog.setTimes((int)times);
            taskJobLog.setStstus(Constant.zero);

            log.info("任务执行完毕，任务ID：" + taskJob.getId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e){
            log.error("任务执行失败，任务ID：" + taskJob.getId(), e);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            taskJobLog.setTimes((int)times);
            taskJobLog.setStstus(Constant.one);
            taskJobLog.setError(StringUtils.substring(e.toString(), 0, 2000));
        }finally {
            taskJobLogMapper.insertSelective(taskJobLog);
        }


    }
}